<template>
    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" :close-on-click-modal="false" @close="cancel">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row>
                <el-col :span="24" style="margin-bottom: 20px"><b>{{ $locale('geWudevice.add.Basic information') }}</b></el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item :label="$locale('geWudevice.add.name')" prop="deviceName">
                        <el-input v-model="form.deviceName" :placeholder="$locale('geWudevice.add.Please enter a name')" style="width: 250px" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item :label="$locale('geWudevice.add.Equipment No')" prop="deviceNum">
                        <el-input v-model="form.deviceNum" :placeholder="$locale('geWudevice.add.Please enter the device number')" style="width: 250px" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item :label="$locale('myDevice.determinedList。add.Equipment source')" prop="deviceSource">
                        <el-input v-model="form.deviceSource" :placeholder="$locale('geWudevice.add.Please enter the device number')" style="width: 250px" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item :label="$locale('geWudevice.add.Equipment pictures')" prop="devicePicture">
                        <ImageUpload @input="changeImage" :value="form.devicePicture" :fileType="['png', 'jpg', 'jpeg']" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24" style="margin-bottom: 20px"><b>{{ $locale('geWudevice.add.Extended Information') }}</b></el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-tabs v-model="activeName" @tab-click="handleClick">
                        <el-tab-pane :label="$locale('geWudevice.add.describe')" name="first">
                            <editor :readOnly="disabled" v-model="form.description" :height="180" />
                        </el-tab-pane>
                        <el-tab-pane :label="$locale('geWudevice.add.technical data')" name="third">
                            <editor :readOnly="disabled" v-model="form.technicalData" :height="180" />
                        </el-tab-pane>
                        <el-tab-pane :label="$locale('geWudevice.add.Related experiments')" name="second" v-if="form.id">
                            <el-input
                                style="width: 250px; margin-bottom: 20px"
                                v-model="queryParams.experimentName"
                                :placeholder="$locale('geWudevice.add.Please enter the name of the experiment you want to search for')"
                                @keyup.enter.native="handleQuery"></el-input>
                            <el-button style="margin-left: 10px" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
                              {{ $locale('geWudevice.add.search for') }}</el-button>
                            <el-table :data="filteredData" ref="table" v-loading="loading" :max-height="160" @select="handleSelectionChange">
                                <el-table-column v-if="!form.id" type="selection" width="55"></el-table-column>
                                <el-table-column :label="$locale('geWudevice.add.Serial Number')" type="index" width="55"></el-table-column>
                                <el-table-column :label="$locale('geWudevice.add.Experiment Name')" align="center" prop="experimentName" width="160"></el-table-column>
                                <el-table-column :label="$locale('geWudevice.add.belong to')" align="center" key="experimentSource" prop="experimentSource" :show-overflow-tooltip="true"></el-table-column>
                                <el-table-column :label="$locale('geWudevice.add.state')" align="center" key="status" prop="status" :show-overflow-tooltip="true">
                                    <template slot-scope="scope">
                                        <span v-for="item in dict.type.experimental_status" :key="item.value">{{ item.value == scope.row.status ? item.label : '' }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column :label="$locale('geWudevice.add.difficulty')" align="center" key="difficultyLevel" prop="difficultyLevel" width="120">
                                    <template slot-scope="scope">{{ scope.row.difficultyLevel }}{{ $locale('geWudevice.add.star') }}</template>
                                </el-table-column>
                                <el-table-column :label="$locale('geWudevice.add.time')" align="center" key="experimentTime" prop="experimentTime">
                                    <template slot-scope="scope">{{ scope.row.experimentTime }}{{ $locale('geWudevice.add.minute') }}</template>
                                </el-table-column>
                                <el-table-column :label="$locale('geWudevice.add.visibility')" align="center" key="isOpen" prop="isOpen">
                                    <template slot-scope="scope">
                                        {{ scope.row.isOpen ? $locale('geWudevice.add.open') : $locale('geWudevice.add.hide') }}
                                    </template>
                                </el-table-column>
                                <!-- <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
                                    <template slot-scope="scope">
                                        <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
                                    </template>
                                </el-table-column> -->
                            </el-table>
                        </el-tab-pane>
                    </el-tabs>
                </el-col>
            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm(0)">{{ $locale('myDevice.determinedList.add.Save draft') }}</el-button>
            <el-button type="primary" @click="submitForm(1)">{{$locale('classList.add.determine')}}</el-button>
            <el-button @click="cancel">{{$locale('classList.add.Cancel')}}</el-button>
        </div>
    </el-dialog>
</template>

<script>
import { getExperimentDeviceListByDeviceId } from '@/api/geWudevice';
import { add, edit, getById } from '@/api/myDevice';
import { getByExperimentName } from '@/api/geWuExperiment';

export default {
    name: 'experimentAdd',
    dicts: ['experimental_status', 'difficulty_level', 'experiment_time', 'experiment_type', 'whether_not'],
    data() {
        return {
            // 遮罩层
            loading: false,
            loadingRemote: false,
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 表单参数
            form: {},
            disabled: false,
            formData: {
                checkList: []
            },
            queryParams: {
                experimentName: '',
                deviceId: undefined
            },
            activeName: 'first',
            filteredData: [],
            experiments: [],
            // 表单校验
            rules: {
                num: [{ required: true, message: this.$locale('geWudevice.add.tip1'), trigger: 'blur' }]
            }
        };
    },
    created() {},
    methods: {
        changeFileTeacher(fileList) {
            this.form.studentGuidebook = fileList;
        },
        changeFileStudent() {
            this.form.teacherGuidebook = fileList;
        },
        // 上传成功
        changeImage(fileList) {
            this.form.devicePicture = fileList;
        },
        // 表单重置
        reset() {
            this.form = {};
            this.resetForm('form');
        },
        /** 新增按钮操作 */
        handleAdd(form) {
            this.reset();
            this.open = true;
            this.title = this.$locale('geWudevice.add.tip2');
            this.handleQuery(); // 先进行搜索
        },
        handleClick() {
            if (this.activeName === 'second') {
                this.$nextTick(() => {
                    this.selectRowsById(this.experiments.map((item) => item.id)); // 保留原选中的数据
                });
            }
        },
        handleSelectionChange(selection, row) {
            const rowId = row.id;
            const index = this.experiments.findIndex((item) => item.id === rowId);
            if (index === -1) {
                this.experiments.push(row);
            } else {
                this.experiments.splice(index, 1);
            }
        },
        async handleUpdate(row, disabled) {
            this.reset();
            this.disabled = disabled;

            // this.form = row
            // this.open = true
            // this.title = disabled ? '查看设备' : '修改设备'
            getById({ id: row.id }).then(({ data }) => {
                this.form = data;
                this.queryParams.deviceId = data.id;
                this.open = true;
                this.title = disabled ? this.$locale('geWudevice.add.tip3') : this.$locale('geWudevice.add.tip4');
                this.handleQuery(); // 先进行搜索
            });
        },
        handleQuery() {
            // 保存当前选中的对象
            if (this.form.id) {
                getExperimentDeviceListByDeviceId(this.queryParams).then(({ data }) => {
                    this.experiments = data;
                    this.filteredData = data;
                    this.$nextTick(() => {
                        this.selectRowsById(this.experiments.map((item) => item.id)); // 保留原选中的数据
                    });
                });
            } else {
                this.getData();
            }
        },
        getData() {
            getByExperimentName(this.queryParams).then(({ data }) => {
                this.filteredData = data;
                this.$nextTick(() => {
                    this.selectRowsById(this.experiments.map((item) => item.id)); // 保留原选中的数据
                });
            });
        },
        selectRowsById(ids) {
            const table = this.$refs.table;
            if (!table) return;
            table.clearSelection(); // 清除所有选中行
            this.filteredData.forEach((row) => {
                if (ids.includes(row.id)) {
                    table.toggleRowSelection(row, true); // 根据 ID 选择对应的行
                }
            });
        },

        /** 提交按钮 */
        submitForm: function (status) {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    this.form.status = status;
                    this.form.experiments = this.experiments; // 提交时包含所有选中的对象数据
                    const saveAction = this.form.id !== undefined ? edit(this.form) : add(this.form);
                    saveAction.then((response) => {
                        this.$modal.msgSuccess(this.form.id !== undefined ? this.$locale('geWudevice.add.tip5') : this.$locale('geWudevice.add.tip6'));
                        this.open = false;
                        this.$emit('getList');
                    });
                }
            });
        },
        // 取消按钮
        cancel() {
            this.queryParams = {
                experimentName: '',
                deviceId: undefined
            };
            this.experiments = [];
            this.activeName = 'first';
            this.open = false;
            this.reset();
        }
    }
};
</script>

<style lang="scss" scoped>
.el-rate {
    line-height: 2;
}
::v-deep .el-table__header-wrapper .el-checkbox {
    display: none;
}
</style>
